#pragma once

#include <iostream>
#include <string>
#include <memory> //智能指针
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "InetAddr.hpp"
#include "Log.hpp"

const std::string gip = "127.0.0.1";
const uint16_t gport = 8888;
const int gblcklog = 5;
#define BUFFERSIZE 4096

class Socket; // 提前声明
using SockPtr = std::shared_ptr<Socket>;

enum
{
    SOCK_ERR,
    BIND_ERR,
    LISTEN_ERR,
    ACCEPT_ERR,
    CONNECT_ERR,
    HEAD_ERR
};

class Socket
{
public:
    virtual void CreateSocketOrDie() = 0;
    virtual void CreateBindOrDie(uint16_t port) = 0;
    virtual void CreateListenOrDie(int backlog = gblcklog) = 0;
    virtual int Accepter(InetAddr *cliaddr) = 0;
    virtual bool Connector(const std::string &peerip, uint16_t peerport) = 0;
    virtual int Sockfd() = 0;
    virtual void Close() = 0;

    virtual ssize_t Recv(std::string *out) = 0;
    virtual ssize_t Send(const std::string &in) = 0;

public:
    void BuildListenSocket(uint16_t port = gport)
    {
        CreateSocketOrDie();
        CreateBindOrDie(port);
        CreateListenOrDie();
    }
    bool BuildClientSocket(std::string ip = gip,uint16_t port = gport)
    {
        CreateSocketOrDie();
        return Connector(ip, port);
    }
};

class tcp_Socket : public Socket
{
public:
    void CreateSocketOrDie() override
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "create sockect failed!\n");
            exit(SOCK_ERR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
    }
    void CreateBindOrDie(uint16_t port = gblcklog) override
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);

        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind failed!\n");
            exit(SOCK_ERR);
        }
        LOG(INFO, "bind success, sockfd: %d\n", _sockfd);
    }
    void CreateListenOrDie(int backlog = gblcklog) override
    {
        if (listen(_sockfd, backlog) < 0)
        {
            LOG(FATAL, "listen failed!\n");
            exit(LISTEN_ERR);
        }
        LOG(INFO, "listen success\n");
    }
    int Accepter(InetAddr *cliaddr) override 
    {//输出型参数，获取客户端地址
        // 服务器连接客户端
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
        if (sockfd < 0)
        {
            LOG(FATAL, "accept failed!\n");
            exit(ACCEPT_ERR);
        }
        *cliaddr = InetAddr(peer);
        LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n", cliaddr->AddrString().c_str(), sockfd);
        return sockfd;
    }
    bool Connector(const std::string &peerip, uint16_t peerport) override
    {
        // 客户端连接服务器
        //填充服务器地址
        struct sockaddr_in server;
        server.sin_addr.s_addr = inet_addr(peerip.c_str());
        server.sin_family = AF_INET;
        server.sin_port = htons(peerport);
        if (connect(_sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            LOG(FATAL, "connect failed!\n");
            exit(ACCEPT_ERR);
        }
        return true;
    }
    int Sockfd() override
    {
        return _sockfd;
    }
    void Close() override
    {
        ::close(_sockfd);
    }
    ssize_t Recv(std::string *out) override
    {
        char inbuffer[10240];
        ssize_t n = recv(_sockfd, inbuffer, sizeof(inbuffer)-1, 0);
        if (n > 0)
        {
            inbuffer[n] = 0;
            *out += inbuffer;
            //std::cout << "---------------------------------------------" << std::endl;
          //  LOG(DEBUG, "n:%d\nstr:\n%s\n", n, (*out).c_str());
        }
        else if (n < 0)
        {
            LOG(FATAL, "recv error!\n");
        }
        return n;
    }
    ssize_t Send(const std::string &in) override
    {
        ssize_t n = send(_sockfd, in.c_str(), in.size(), 0);
        if (n < 0)
        {
            LOG(FATAL, "send error!\n");
        }
        return n;
    }

public:
    tcp_Socket(int sockfd)
        : _sockfd(sockfd)
    {
    }
    tcp_Socket()
    {
    }

private:
    int _sockfd; // 可以是监听套接字，也可以是普通套接字
};